<template>
  <div>
    <div class="container">
      <div class="form">
        <h2>登录</h2>
        <form @keyup.enter="login">
          <div class="inputBox">
            <input type="text" placeholder="账号" v-model="userAccount">
          </div>
          <div class="inputBox">
            <input type="password" placeholder="密码" v-model="password">
          </div>
          <div class="inputBox">
            <input type="button" @click="login" value="登录">
            <h4 class="login-error" v-if="loginError">{{errorMessage}}</h4>
          </div>
          <p class="forget">忘记密码?<a>点击这里</a></p>
          <p class="forget">没有账户?<a @click="register">注册</a></p>
        </form>
      </div>
    </div>
  </div>
</template>

<script>

import http from "@/util/request";

export default {
  name: "Login",
  data(){
    return{
      userAccount: '',
      password: '',
      errorMessage:'',
      loginError: false
    }
  },
  methods: {
    register(){
      this.$router.push('register');
    },
    login(){
      http.post('/login',{
        userAccount: this.userAccount,
        password: this.password
      }).then((response)=> {
        //获取服务器返回的用户信息
        let userInfo = response.data;

        if(userInfo && userInfo.userId){
          // 如果用户信息存在，并且查询到userId也存在则登录成功
          this.loginError = false;
          sessionStorage.setItem('userName', userInfo.realName);
          this.$router.push('MainPage');
        }else{
          //否则登录失败
          this.loginError = true;
          this.errorMessage = "账号或者密码错误！！！";
        }
      }).catch((error)=>{
        this.loginError = true;
        if (error.response) {
          this.errorMessage = "服务器错误："+error.message;
        } else if (error.request) {
          this.errorMessage = "请求错误："+error.message;
        } else {
          this.errorMessage = "未知错误："+error.message;
        }
      });
    }
  }
}
</script>

<style scoped>
@import '~assets/css/login.css';

.forget {
  margin-top: 6px;
  color: #fff;
  letter-spacing: 1px;
}

.forget a {
  color: #fff;
  font-weight: 600;
  text-decoration: none;
  cursor:pointer;
}
</style>